package router

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func AllowAllCors() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 允许所有来源访问
		c.Header("Access-Control-Allow-Origin", "*")

		// 允许的请求方法
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")

		// 允许的请求头
		c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")

		// 允许前端读取的响应头
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin")

		// 预检请求缓存时间（24小时）
		c.Header("Access-Control-Max-Age", "86400")

		// 专门处理OPTIONS预检请求
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}
